using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Threading;
using System.CodeDom;
using System.Globalization;
using System.IO;
using System.Resources;
using NutriStat.Statistics;

namespace NutriStat
{
    /// <summary>
    /// Configruation options form
    /// </summary>
    public partial class OptionsDialog : NutriDialog
    {
        #region Data
        #region Protected Data
        #endregion Protected Data

        #region Private Data
        private FormMainMenu menu;
        private NutriConfig config;
        #endregion Private Data

        #region Internal Data
        //internal List<string> recentFiles;
        #endregion Internal Data
        #endregion Data

        #region Constructors
        /// <summary>
        /// The constructor for the options menu
        /// </summary>
        public OptionsDialog()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Custom constructor used for passing the main menu and configuration objects
        /// to the options menu.
        /// </summary>
        /// <param name="mainMenu">The main menu form.</param>        
        /// <param name="mainConfig">The program's current configuration settings.</param>
        public OptionsDialog(FormMainMenu mainMenu, NutriConfig mainConfig)
        {
            InitializeComponent();            

            menu = mainMenu;
            config = new NutriConfig(mainConfig);            
        }
        #endregion Constructors

        #region Events
        /// <summary>
        /// Handles the click event for the Cancel button
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handles the click event for the OK button
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void buttonOK_Click(object sender, EventArgs e)
        {   
            WriteConfigFile();
            
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(config.CultureCode);
            string baseName = "NutriStat" + ".Strings";
            ResourceManager rm = new ResourceManager(baseName,
               typeof(Program).Assembly);

            menu.LoadConfigFile(config);            

            this.Close();
        }       

        /// <summary>
        /// Handles the click event for the 'Reset to Defaults' button on the GRAPH tab
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void buttonReset_Click(object sender, EventArgs e)
        {
            SetGraphTabControlsToDefaults();
        }

        /// <summary>
        /// Handles the Load event for the options menu
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void OptionsDialog_Load(object sender, EventArgs e)
        {
            ConfigureFormControls();
            
            bool success = false;
            success = LoadConfigFile();
        }

        /// <summary>
        /// Handles the CheckChanged event for the CDC radio button
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void radioButtonCDC_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonCDC.Checked)
            {
                checkBoxHead.Enabled = true;
                checkBoxHeadEntry.Enabled = true;
                checkBoxBMI.Enabled = true;
                checkBoxWH.Enabled = true;

                checkBoxSSF.Checked = false;
                checkBoxSSF.Enabled = false;
                checkBoxTSF.Checked = false;
                checkBoxTSF.Enabled = false;

                checkBoxMUAC.Checked = false;
                checkBoxMUAC.Enabled = false;
            }
        }

        /// <summary>
        /// Handles the CheckChanged event for the WHO 2007 radio button
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void radioButtonWHO2007_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonWHO2007.Checked)
            {
                checkBoxHead.Checked = false;
                checkBoxHead.Enabled = false;                

                checkBoxSSF.Checked = false;
                checkBoxSSF.Enabled = false;
                checkBoxTSF.Checked = false;
                checkBoxTSF.Enabled = false;

                checkBoxMUAC.Checked = false;
                checkBoxMUAC.Enabled = false;

                checkBoxWH.Checked = false;
                checkBoxWH.Enabled = false;

                checkBoxBMI.Enabled = true;
                checkBoxHA.Enabled = true;
                checkBoxWA.Enabled = true;
            }
        }

        /// <summary>
        /// Handles the CheckChanged event for the WHO 2006 radio button
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void radioButtonWHO2006_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonWHO2006.Checked)
            {
                checkBoxHead.Enabled = true;
                checkBoxHeadEntry.Enabled = true;
                checkBoxBMI.Enabled = true;
                checkBoxWH.Enabled = true;
                checkBoxSSF.Enabled = true;
                checkBoxTSF.Enabled = true;
                checkBoxMUAC.Enabled = true;
            }
        }

        /// <summary>
        /// Handles the CheckChanged event for the CDC/WHO 1978 radio button
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void radioButtonWHO1978_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonWHO1978.Checked)
            {
                checkBoxHead.Checked = false;
                checkBoxBMI.Checked = false;

                checkBoxHead.Enabled = false;
                checkBoxBMI.Enabled = false;
                checkBoxWH.Enabled = true;

                checkBoxSSF.Checked = false;
                checkBoxSSF.Enabled = false;
                checkBoxTSF.Checked = false;
                checkBoxTSF.Enabled = false;

                checkBoxMUAC.Checked = false;
                checkBoxMUAC.Enabled = false;
            }
        }

        /// <summary>
        /// Handles the click event for the CDC radio button
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void radioButtonCDC_Click(object sender, EventArgs e)
        {
            return;
            /*
            DialogResult result = MessageBox.Show(this, "This action will change the growth reference standard upon " +
                "which the statistic calculations are based.", "Change Reference Standard",
                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
             */

        }

        /// <summary>
        /// Handles the CheckChanged event for the WHO 2007 radio button
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void radioButtonWHO2007_Click(object sender, EventArgs e)
        {
            return;
            /*
            DialogResult result = MessageBox.Show(this, "This action will change the growth reference standard upon " +
                "which the statistic calculations are based.", "Change Reference Standard",
                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
             */
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event for the ComboMeasurements list box
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void comboBoxMeasurements_SelectedIndexChanged(object sender, EventArgs e)
        {            
        }

        /// <summary>
        /// Handles the click event for all color panels
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void panelColor_Click(object sender, EventArgs e)
        {
            DialogResult result = colorDialogPrimary.ShowDialog(this);
            if (!result.Equals(DialogResult.Cancel))
            {                
                Panel tempPanel = (Panel)sender;
                tempPanel.BackColor = colorDialogPrimary.Color;
            }
        }
        #endregion Event Handlers

        #region Methods
        #region Public Methods
        #endregion Public Methods

        #region Protected Methods
        /// <summary>
        /// Configures the form controls based on the user's preferences, as defined in the options.        
        /// </summary>
        protected internal override void ConfigureFormControls()
        {
            SetGraphTabControlsToDefaults();

            comboBoxMeasurementArm.Items.Clear();
            comboBoxMeasurementArm.Items.Add(MeasurementUnits.Centimeter.FullName);
            comboBoxMeasurementArm.Items.Add(MeasurementUnits.Inch.FullName);

            comboBoxMeasurementHead.Items.Clear();
            comboBoxMeasurementHead.Items.Add(MeasurementUnits.Centimeter.FullName);
            comboBoxMeasurementHead.Items.Add(MeasurementUnits.Inch.FullName);

            comboBoxMeasurementHeight.Items.Clear();
            comboBoxMeasurementHeight.Items.Add(MeasurementUnits.Centimeter.FullName);
            comboBoxMeasurementHeight.Items.Add(MeasurementUnits.Inch.FullName);

            comboBoxMeasurementSkinFold.Items.Clear();
            comboBoxMeasurementSkinFold.Items.Add(MeasurementUnits.Millimeter.FullName);
            comboBoxMeasurementSkinFold.Items.Add(MeasurementUnits.Inch.FullName);

            comboBoxMeasurementWeight.Items.Clear();
            comboBoxMeasurementWeight.Items.Add(MeasurementUnits.Kilogram.FullName);
            comboBoxMeasurementWeight.Items.Add(MeasurementUnits.Pound.FullName);

            comboBoxMeasurements.Items.Add(SharedStrings.METRIC);
            comboBoxMeasurements.Items.Add(SharedStrings.CUSTOMARY);
            comboBoxMeasurements.Items.Add(SharedStrings.CUSTOM);

            this.Text = SharedStrings.OPTIONS;
            groupBoxReference.Text = SharedStrings.GROWTH_REFERENCE;
            groupBoxDataEntryFields.Text = SharedStrings.DATA_ENTRY_FIELDS;
            groupBoxStatistics.Text = SharedStrings.STATISTICS;
            groupBoxResults.Text = SharedStrings.RESULTS;
            checkBoxEnableDelete.Text = SharedStrings.ENABLE_DELETE_BUTTON;

            checkBoxName.Text = SharedStrings.NAME;
            checkBoxDOB.Text = SharedStrings.DATE_OF_BIRTH;
            checkBoxAge.Text = SharedStrings.AGE;
            checkBoxHeight.Text = SharedStrings.HEIGHT;
            checkBoxWeight.Text = SharedStrings.WEIGHT;
            checkBoxEdema.Text = SharedStrings.EDEMA;
            checkBoxHeadEntry.Text = SharedStrings.HEAD_CIRCUMFERENCE;
            checkBoxMUACEntry.Text = SharedStrings.ARM_CIRCUMFERENCE_MUAC;
            checkBoxSSFEntry.Text = SharedStrings.SUBSCAPULAR_SKIN_FOLD;
            checkBoxTSFEntry.Text = SharedStrings.TRICEPS_SKIN_FOLD;
            checkBoxNotes.Text = SharedStrings.NOTES;

            checkBoxHA.Text = SharedStrings.HEIGHT_FOR_AGE;
            checkBoxWA.Text = SharedStrings.WEIGHT_FOR_AGE;
            checkBoxWH.Text = SharedStrings.WEIGHT_FOR_HEIGHT;
            checkBoxFlag.Text = SharedStrings.FLAG;
            checkBoxBMI.Text = SharedStrings.BODY_MASS_INDEX;
            checkBoxHead.Text = SharedStrings.HEAD_CIRCUMFERENCE_FOR_AGE;
            checkBoxMUAC.Text = SharedStrings.ARM_CIRCUMFERENCE_MUAC;
            checkBoxSSF.Text = SharedStrings.SUBSCAPULAR_SKIN_FOLD_FOR_AGE;
            checkBoxTSF.Text = SharedStrings.TRICEPS_SKIN_FOLD_FOR_AGE;

            checkBoxPercentiles.Text = SharedStrings.PERCENTILES;
            checkBoxZScores.Text = SharedStrings.Z_SCORES;
            checkBoxMedian.Text = SharedStrings.PERCENT_OF_MEDIAN;

            checkBoxColorCoding.Text = SharedStrings.USE_COLOR_CODED_OUTPUT;
            checkBoxMUACOld.Text = SharedStrings.SHOW_LEGACY_MUAC;

            tabControlOptions.TabPages[0].Text = SharedStrings.DISPLAY;
            tabControlOptions.TabPages[1].Text = SharedStrings.UNITS;
            tabControlOptions.TabPages[2].Text = SharedStrings.LANGUAGE;

            PopulateLanguages(Directory.GetCurrentDirectory());
            listBoxLanguages.Items.Add("English (United States)");

            // Highlight the language that is currently set in the program's configuration XML file
            CultureInfo tempCult = new CultureInfo(config.CultureCode);
            for (int i = 0; i < listBoxLanguages.Items.Count; i++)
            {
                if (tempCult.EnglishName == listBoxLanguages.Items[i].ToString())
                {
                    listBoxLanguages.SelectedItem = listBoxLanguages.Items[i];
                }
            }
        }
        #endregion Protected Methods

        #region Private Methods
        /// <summary>
        /// Resets all controls on the 'Graph' tab to their defaults
        /// </summary>
        private void SetGraphTabControlsToDefaults()
        {
            numericUpDownP1thick.Value = 0;
            numericUpDownP3thick.Value = 1;
            numericUpDownP5thick.Value = 1;
            numericUpDownP10thick.Value = 1;
            numericUpDownP25thick.Value = 1;
            numericUpDownP50thick.Value = 2;
            numericUpDownP85thick.Value = 1;

            numericUpDown3SD.Value = 2;
            numericUpDown2SD.Value = 2;
            numericUpDown1SD.Value = 2;
            numericUpDownMedian.Value = 2;
            
            numericUpDownNormalCurve.Value = 2;
            numericUpDownPatientDataPointSize.Value = 9;
            numericUpDownPatientDataPointBorder.Value = 1.6m;

            panelColorP1.BackColor = Color.Maroon;
            panelColorP3.BackColor = Color.Red;
            panelColorP5.BackColor = Color.Orange;
            panelColorP10.BackColor = Color.Violet;
            panelColorP25.BackColor = Color.Green;
            panelColorP50.BackColor = Color.Blue;
            panelColorP85.BackColor = Color.Brown;

            panelColorPatientCurve.BackColor = Color.Black;
            panelColorPatientDataPointBorder.BackColor = Color.Red;
            panelColorPatientDataPointFill.BackColor = Color.Black;

            panelColor3SD.BackColor = Color.Red;
            panelColor2SD.BackColor = Color.Orange;
            panelColor1SD.BackColor = Color.Green;
            panelColorMedian.BackColor = Color.Blue;
            panelColorNormalCurve.BackColor = Color.CornflowerBlue;
        }

        private Color GetColorFromConfig(string rgb)
        {
            #region Input Validation
            if (rgb.Length > 11 || rgb.Length < 5)
            {
                return Color.Black;
            }
            #endregion Input Validation
            string[] pieces = rgb.Split(',');            

            int r = Int32.Parse(pieces[0]);
            int g = Int32.Parse(pieces[1]);
            int b = Int32.Parse(pieces[2]);

            return Color.FromArgb(r, g, b);
        }

        private string GetColorStringForConfig(Color color)
        {
            string r = color.R.ToString();
            string g = color.G.ToString();
            string b = color.B.ToString();
            return r + "," + g + "," + b;
        }        

        /// <summary>
        /// Populates the language list box in the Options menu with all of the available
        /// language translations. This is a recursive function.
        /// </summary>
        /// <param name="directory">The directory to search.</param>
        private void PopulateLanguages(string directory)
        {
            // recursively loop through each subdirectory and look for directories that contain
            // the NutriStat.resources.dll (translation) file. If we find one, grab the directory
            // name and create a new CultureInfo object from it. Once this is complete, we can
            // use the four-letter code to generate the full English name and add that name to
            // our list box.

            // References: Adapted from http://support.microsoft.com/kb/303974
            try
            {
                foreach (string d in Directory.GetDirectories(directory))
                {
                    foreach (string f in Directory.GetFiles(d, "NutriStat.resources.dll"))
                    {
                        string temp = f;
                        temp = temp.Replace(Directory.GetCurrentDirectory(), "");
                        temp = temp.Replace("NutriStat.resources.dll", "");
                        temp = temp.Replace("/", "");
                        temp = temp.Replace("\\", "");
                        CultureInfo tempCult = new CultureInfo(temp);                        
                        listBoxLanguages.Items.Add(tempCult.EnglishName);                        
                    }
                    PopulateLanguages(d);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Strips the XML tags off a line of text
        /// </summary>
        /// <param name="line">The string to be stripped of its XML characters</param>        
        /// <returns>string</returns>
        private string ConfigValueParser(string line)
        {
            #region Input Validation
            if (line.Length <= 0 || line.Length >= 512)
            {
                throw new Exception("Parameter out of bounds.");
            }
            #endregion
            int last = line.LastIndexOf("<");
            int first = 1 + line.IndexOf(">");
            string value = line.Substring(first, last - first);
            value.TrimStart(' ');
            value.TrimEnd(' ');           

            return value;
        }

        /// <summary>
        /// Loads configuration settings from the configuration file.
        /// </summary>
        /// <returns>bool</returns>
        private bool LoadConfigFile()
        {            
            try
            { /*
                if (config.MeasurementSystem.Equals("customary"))
                {
                    comboBoxMeasurements.Text = "Customary";
                }
                else
                {
                    comboBoxMeasurements.Text = "Metric";
                }
                */
                int precisionZ = config.PrecisionZ;
                int precisionC = config.PrecisionC;

                switch (precisionZ)
                {
                    case 1:
                        comboBoxPrecisionZ.Text = "1";
                        break;
                    case 2:
                        comboBoxPrecisionZ.Text = "2";
                        break;
                    case 3:
                        comboBoxPrecisionZ.Text = "3";
                        break;
                    case 4:
                        comboBoxPrecisionZ.Text = "4";
                        break;
                    default:
                        comboBoxPrecisionZ.Text = "3";
                        break;
                }

                switch (precisionC)
                {
                    case 1:
                        comboBoxPrecisionC.Text = "1";
                        break;
                    case 2:
                        comboBoxPrecisionC.Text = "2";
                        break;
                    case 3:
                        comboBoxPrecisionC.Text = "3";
                        break;
                    case 4:
                        comboBoxPrecisionC.Text = "4";
                        break;
                    default:
                        comboBoxPrecisionC.Text = "3";
                        break;
                }                    
                if (config.ReferenceType.Equals(GrowthReferenceTypes.WHO2006))
                {
                            radioButtonCDC.Checked = false;
                            radioButtonWHO2006.Checked = true;
                            radioButtonWHO2007.Checked = false;
                            radioButtonWHO1978.Checked = false;
                }
                else if (config.ReferenceType.Equals(GrowthReferenceTypes.WHO2007))
                {
                            radioButtonCDC.Checked = false;
                            radioButtonWHO2006.Checked = false;
                            radioButtonWHO2007.Checked = true;                            
                            radioButtonWHO1978.Checked = false;
                }
                else if (config.ReferenceType.Equals(GrowthReferenceTypes.CDC2000))
                {
                    radioButtonCDC.Checked = true;
                    radioButtonWHO2006.Checked = false;
                    radioButtonWHO2007.Checked = false;
                    radioButtonWHO1978.Checked = false;
                }
                else // if (config.ReferenceType == GrowthReferenceTypes.WHO1978)
                {
                    radioButtonCDC.Checked = false;
                    radioButtonWHO2006.Checked = false;
                    radioButtonWHO2007.Checked = false;
                    radioButtonWHO1978.Checked = true;

                    checkBoxBMI.Checked = false;
                    checkBoxBMI.Enabled = false;

                    checkBoxHead.Checked = false;
                    checkBoxHead.Enabled = false;
                }

                if (!config.ColorCoding.Equals("1"))
                {
                    checkBoxColorCoding.Checked = false;
                }
                else
                {
                    checkBoxColorCoding.Checked = true;
                }

                checkBoxShowSurveyFields.Checked = config.SurveyFields;
                checkBoxEnableDelete.Checked = config.DeleteButton;
                checkBoxName.Checked = config.Name;
                checkBoxDOB.Checked = config.Birthdate;
                checkBoxEdema.Checked = config.Edema;
                checkBoxAge.Checked = config.Age;
                checkBoxNotes.Checked = config.Notes;
                checkBoxHeight.Checked = config.Height;
                checkBoxWeight.Checked = config.Weight;
                checkBoxHeadEntry.Checked = config.HeadCircumference;
                checkBoxMUACEntry.Checked = config.ArmCircumference;
                checkBoxSSFEntry.Checked = config.SubscapularSkinFold;
                checkBoxTSFEntry.Checked = config.TricepsSkinFold;

                checkBoxHA.Checked = config.ResultsHA;
                checkBoxWA.Checked = config.ResultsWA;
                checkBoxWH.Checked = config.ResultsWH;
                checkBoxBMI.Checked = config.ResultsBMI;
                checkBoxFlag.Checked = config.ResultsFlag;
                checkBoxHead.Checked = config.ResultsHead;
                checkBoxMUAC.Checked = config.ResultsArm;
                checkBoxSSF.Checked = config.ResultsSSF;
                checkBoxTSF.Checked = config.ResultsTSF;
                checkBoxMUACOld.Checked = config.ResultsLegacyArm;

                checkBoxPercentiles.Checked = config.StatsPercentiles;
                checkBoxZScores.Checked = config.StatsZScores;
                checkBoxMedian.Checked = config.StatsPercentOfMedian;

                if (config.UnitsArm.Equals(MeasurementUnits.Centimeter.Abbreviation))
                {
                    comboBoxMeasurementArm.Text = MeasurementUnits.Centimeter.FullName;
                }
                else
                {
                    comboBoxMeasurementArm.Text = MeasurementUnits.Inch.FullName;
                }

                if (config.UnitsHead.Equals(MeasurementUnits.Centimeter.Abbreviation))
                {
                    comboBoxMeasurementHead.Text = MeasurementUnits.Centimeter.FullName;
                }
                else
                {
                    comboBoxMeasurementHead.Text = MeasurementUnits.Inch.FullName;
                }

                if (config.UnitsHeight.Equals(MeasurementUnits.Centimeter.Abbreviation))
                {
                    comboBoxMeasurementHeight.Text = MeasurementUnits.Centimeter.FullName;
                }
                else
                {
                    comboBoxMeasurementHeight.Text = MeasurementUnits.Inch.FullName;
                }

                if (config.UnitsSkin.Equals(MeasurementUnits.Millimeter.Abbreviation))
                {
                    comboBoxMeasurementSkinFold.Text = MeasurementUnits.Millimeter.FullName;
                }
                else
                {
                    comboBoxMeasurementSkinFold.Text = MeasurementUnits.Inch.FullName;
                }

                if (config.UnitsWeight.Equals(MeasurementUnits.Kilogram.Abbreviation))
                {
                    comboBoxMeasurementWeight.Text = MeasurementUnits.Kilogram.FullName;
                }
                else
                {
                    comboBoxMeasurementWeight.Text = MeasurementUnits.Pound.FullName;
                }


                panelColorP1.BackColor = GetColorFromConfig(config.ColorP1);
                panelColorP3.BackColor = GetColorFromConfig(config.ColorP3);
                panelColorP5.BackColor = GetColorFromConfig(config.ColorP5);
                panelColorP10.BackColor = GetColorFromConfig(config.ColorP10);
                panelColorP25.BackColor = GetColorFromConfig(config.ColorP25);
                panelColorP50.BackColor = GetColorFromConfig(config.ColorP50);
                panelColorP85.BackColor = GetColorFromConfig(config.ColorP85);
                
                numericUpDownP1thick.Value = config.ThickP1;
                numericUpDownP3thick.Value = config.ThickP3;
                numericUpDownP5thick.Value = config.ThickP5;
                numericUpDownP10thick.Value = config.ThickP10;
                numericUpDownP25thick.Value = config.ThickP25;
                numericUpDownP50thick.Value = config.ThickP50;
                numericUpDownP85thick.Value = config.ThickP85;

                panelColorPatientCurve.BackColor = GetColorFromConfig(config.ColorPatientCurve);
                panelColorPatientDataPointBorder.BackColor = GetColorFromConfig(config.ColorPatientDataPointBorder);
                panelColorPatientDataPointFill.BackColor = GetColorFromConfig(config.ColorPatientDataPointFill);

                numericUpDownPatient.Value = config.ThickPatientCurve;
                numericUpDownPatientDataPointBorder.Value = Convert.ToDecimal(config.ThickPatientDataPointBorder);

                panelColor3SD.BackColor = GetColorFromConfig(config.Color3SD);
                panelColor2SD.BackColor = GetColorFromConfig(config.Color2SD);
                panelColor1SD.BackColor = GetColorFromConfig(config.Color1SD);
                panelColorMedian.BackColor = GetColorFromConfig(config.ColorMedian);
                
                numericUpDown3SD.Value = config.Thick3SD;
                numericUpDown2SD.Value = config.Thick2SD;
                numericUpDown1SD.Value = config.Thick1SD;
                numericUpDownMedian.Value = config.ThickMedian;

                panelColorNormalCurve.BackColor = GetColorFromConfig(config.ColorNormalCurve);
                numericUpDownNormalCurve.Value = config.ThickNormalCurve;

                numericUpDownPatientDataPointSize.Value = config.PatientDataPointSize;
                checkBoxTransparentFill.Checked = config.TransparentDataPoints;

                checkBoxLegend.Checked = config.ShowLegend;
                checkBoxCoordinateCursor.Checked = config.ShowCoordinateCursor;
                checkBoxLabels.Checked = config.ShowDataPointLabels;
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }

            return true;
        }

        /// <summary>
        /// Writes the current configuration settings to an XML file.
        /// </summary>
        /// <returns>bool</returns>
        private bool WriteConfigFile()
        {
            try
            {
                if (comboBoxMeasurements.Text.Equals("Customary"))
                {
                    config.MeasurementSystem = "customary";
                }
                else
                {
                    config.MeasurementSystem = "metric";
                }

                if (radioButtonWHO2006.Checked)
                    config.ReferenceType = GrowthReferenceTypes.WHO2006;
                else if (radioButtonWHO2007.Checked)
                    config.ReferenceType = GrowthReferenceTypes.WHO2007;
                else if (radioButtonCDC.Checked)                
                    config.ReferenceType = GrowthReferenceTypes.CDC2000;
                else // if 
                    config.ReferenceType = GrowthReferenceTypes.WHO1978;

                if (checkBoxColorCoding.Checked)
                {
                    config.ColorCoding = "1";
                }
                else
                {
                    config.ColorCoding = "0";
                }

                string precisionZ = comboBoxPrecisionZ.Text;
                string precisionC = comboBoxPrecisionC.Text;

                switch (precisionZ)
                {
                    case "1":
                        config.PrecisionZ = 1;
                        break;
                    case "2":
                        config.PrecisionZ = 2;
                        break;
                    case "3":
                        config.PrecisionZ = 3;
                        break;
                    case "4":
                        config.PrecisionZ = 4;
                        break;
                    default:
                        config.PrecisionZ = 3;
                        break;
                }

                switch (precisionC)
                {
                    case "1":
                        config.PrecisionC = 1;
                        break;
                    case "2":
                        config.PrecisionC = 2;
                        break;
                    case "3":
                        config.PrecisionC = 3;
                        break;
                    case "4":
                        config.PrecisionC = 4;
                        break;
                    default:
                        config.PrecisionC = 3;
                        break;
                }
                
                // Get the culture code based off the selected item in the language list box
                string selectedCulture = listBoxLanguages.SelectedItem.ToString();                
                System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");                
                selectedCulture = TypeDescriptor.GetConverter(culture).ConvertFrom(selectedCulture).ToString();
                config.CultureCode = selectedCulture;
                config.DeleteButton = checkBoxEnableDelete.Checked;
                config.SurveyFields = checkBoxShowSurveyFields.Checked;
                config.Name = checkBoxName.Checked;
                config.Birthdate = checkBoxDOB.Checked;
                config.Edema = checkBoxEdema.Checked;
                config.Age = checkBoxAge.Checked;
                config.Notes = checkBoxNotes.Checked;
                config.Height = checkBoxHeight.Checked;
                config.Weight = checkBoxWeight.Checked;
                config.HeadCircumference = checkBoxHeadEntry.Checked;
                config.ArmCircumference = checkBoxMUACEntry.Checked;
                config.SubscapularSkinFold = checkBoxSSFEntry.Checked;
                config.TricepsSkinFold = checkBoxTSFEntry.Checked;

                config.ResultsHA = checkBoxHA.Checked;
                config.ResultsWA = checkBoxWA.Checked;
                config.ResultsWH = checkBoxWH.Checked;
                config.ResultsBMI = checkBoxBMI.Checked;
                config.ResultsFlag = checkBoxFlag.Checked;
                config.ResultsHead = checkBoxHead.Checked;
                config.ResultsArm = checkBoxMUAC.Checked;
                config.ResultsSSF = checkBoxSSF.Checked;
                config.ResultsTSF = checkBoxTSF.Checked;
                config.ResultsLegacyArm = checkBoxMUACOld.Checked;

                config.StatsPercentiles = checkBoxPercentiles.Checked;
                config.StatsZScores = checkBoxZScores.Checked;
                config.StatsPercentOfMedian = checkBoxMedian.Checked;

                if (comboBoxMeasurementArm.Text.Equals(MeasurementUnits.Centimeter.FullName))
                    config.UnitsArm = MeasurementUnits.Centimeter.Abbreviation;
                else
                    config.UnitsArm = MeasurementUnits.Inch.Abbreviation;

                if (comboBoxMeasurementHead.Text.Equals(MeasurementUnits.Centimeter.FullName))
                    config.UnitsHead = MeasurementUnits.Centimeter.Abbreviation;
                else
                    config.UnitsHead = MeasurementUnits.Inch.Abbreviation;

                if (comboBoxMeasurementHeight.Text.Equals(MeasurementUnits.Centimeter.FullName))
                    config.UnitsHeight = MeasurementUnits.Centimeter.Abbreviation;
                else
                    config.UnitsHeight = MeasurementUnits.Inch.Abbreviation;

                if (comboBoxMeasurementSkinFold.Text.Equals(MeasurementUnits.Millimeter.FullName))
                    config.UnitsSkin = MeasurementUnits.Millimeter.Abbreviation;
                else
                    config.UnitsSkin = MeasurementUnits.Inch.Abbreviation;

                if (comboBoxMeasurementWeight.Text.Equals(MeasurementUnits.Kilogram.FullName))
                    config.UnitsWeight = MeasurementUnits.Kilogram.Abbreviation;
                else
                    config.UnitsWeight = MeasurementUnits.Pound.Abbreviation;

                config.ColorP1 = GetColorStringForConfig(panelColorP1.BackColor);
                config.ColorP3 = GetColorStringForConfig(panelColorP3.BackColor);
                config.ColorP5 = GetColorStringForConfig(panelColorP5.BackColor);
                config.ColorP10 = GetColorStringForConfig(panelColorP10.BackColor);
                config.ColorP25 = GetColorStringForConfig(panelColorP25.BackColor);
                config.ColorP50 = GetColorStringForConfig(panelColorP50.BackColor);
                config.ColorP85 = GetColorStringForConfig(panelColorP85.BackColor);
                
                config.ThickP1 = Convert.ToInt32(numericUpDownP1thick.Value);
                config.ThickP3 = Convert.ToInt32(numericUpDownP3thick.Value);
                config.ThickP5 = Convert.ToInt32(numericUpDownP5thick.Value);
                config.ThickP10 = Convert.ToInt32(numericUpDownP10thick.Value);
                config.ThickP25 = Convert.ToInt32(numericUpDownP25thick.Value);
                config.ThickP50 = Convert.ToInt32(numericUpDownP50thick.Value);
                config.ThickP85 = Convert.ToInt32(numericUpDownP85thick.Value);

                config.ColorPatientCurve = GetColorStringForConfig(panelColorPatientCurve.BackColor);
                config.ColorPatientDataPointBorder = GetColorStringForConfig(panelColorPatientDataPointBorder.BackColor);
                config.ColorPatientDataPointFill = GetColorStringForConfig(panelColorPatientDataPointFill.BackColor);

                config.ThickPatientCurve = Convert.ToInt32(numericUpDownPatient.Value);
                config.ThickPatientDataPointBorder = Convert.ToDouble(numericUpDownPatientDataPointBorder.Value);

                config.Color3SD = GetColorStringForConfig(panelColor3SD.BackColor);
                config.Color2SD = GetColorStringForConfig(panelColor2SD.BackColor);
                config.Color1SD = GetColorStringForConfig(panelColor1SD.BackColor);
                config.ColorMedian = GetColorStringForConfig(panelColorMedian.BackColor);
                
                config.Thick3SD = Convert.ToInt32(numericUpDown3SD.Value);
                config.Thick2SD = Convert.ToInt32(numericUpDown2SD.Value);
                config.Thick1SD = Convert.ToInt32(numericUpDown1SD.Value);
                config.ThickMedian = Convert.ToInt32(numericUpDownMedian.Value);

                config.ColorNormalCurve = GetColorStringForConfig(panelColorNormalCurve.BackColor);
                config.ThickNormalCurve = Convert.ToInt32(numericUpDownNormalCurve.Value);

                config.PatientDataPointSize = Convert.ToInt32(numericUpDownPatientDataPointSize.Value);
                config.TransparentDataPoints = checkBoxTransparentFill.Checked;

                config.ShowLegend = checkBoxLegend.Checked;
                config.ShowDataPointLabels = checkBoxLabels.Checked;
                config.ShowCoordinateCursor = checkBoxCoordinateCursor.Checked;

                config.WriteConfigFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }

            return true;
        }
        #endregion Private Methods
        #endregion Methods
    }
}